package top.hepingan.cloudsystem.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.hepingan.cloudcommon.entity.User;
import top.hepingan.cloudcommon.exceptions.LoginPasswordException;
import top.hepingan.cloudcommon.exceptions.RegistrationException;
import top.hepingan.cloudcommon.msg.Result;
import top.hepingan.cloudsystem.service.AuthService;

/**
 * 登录授权接口
 *
 * @author  @github dulaiduwang003
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    /**
     * 登录账号
     *
     * @param user user
     * @return the result
     */
    @PostMapping(value = "/login", name = "登录", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result emailLogin(@RequestBody @Validated final User user) {
        try {
            return Result.data(authService.login(user));
        } catch (LoginPasswordException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 注册账号
     *
     * @param user user
     * @return the result
     */
    @PostMapping(value = "/register", name = "注册账号", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result register(@RequestBody @Validated final User user) {
        try {
            authService.register(user);
            return Result.ok();
        } catch (RegistrationException e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping(value = "/detail" , name = "获取用户信息")
    public Result detail(@RequestParam Integer userId) {
        return Result.data(authService.detail(userId));
    }
}
